const { Clients } = require("../models/clientsModel");
let jwt = require("jsonwebtoken")
const { moveFiles, removeFiles } = require('../utils/upload');


async function register(req, res, next) {
    const { username, password } = req.body
    console.info(username)
    const userAlreadyExists = await Clients.find({ username })
    if (userAlreadyExists.length > 0) {
        res.send({
            msg: "User already exists, try use other username",
            status: 0
        })
    } else {
        await Clients.create({ username, password })
        res.send({
            msg: "register success",
            status: 1
        })
    }

}

async function login(req, res, next) {
    const { username, password } = req.body
    const data = await Clients.find({ username, password })
    if (data.length > 0) {
        let token = jwt.sign(
            { username },
            "iouhfioahufh",
            { expiresIn: 60 * 100 },
        )
        res.send({
            token,
            met: "login success",
            status: 1,
        })
    } else {
        res.send({
            msg: "login failed",
            status: 0
        })
    }
}
// 获取客户
async function getClient(req, res, next) {  
        const {_id, pageSize = 10, currentPage = 1 } = req.query;
        // 总条数
        const total = await Clients.countDocuments();
        // 总页数
        const totalPages = Math.ceil(total / pageSize);
        const data = await Clients
        .find( _id )
        .limit(pageSize - 0) 
        .skip((currentPage - 1) * pageSize)
        .populate("salesId")
        .populate("ordersId")
        .populate({
            //保险产品
            path: "insurancesId",
            //保险类型
            populate: { path: 'insuranceTypeId' }
        })
        res.send({
            status: 1,
            data: { total, totalPages, data, pageSize, currentPage },
            message: '获取客户成功'
        })
        res.send({
            status: 0,
            message: '获取客户失败'
        })
}
// 修改客户信息
async function updateClient(req, res, next) {
    try {
        const { _id, username, age, gender } = req.body;
        const data = await Clients.updateOne({ _id }, { username, age, gender })
        res.send({
            status: 1,
            data,
            message: '修改客户成功'
        })
    } catch (error) {
        res.send({
            status: 0,
            data,
            message: '修改客户失败'
        })
    }
}
// 删除客户
async function deletClient(req, res, next) {
    try {
        const { _id } = req.body;
        const data = await Clients.findByIdAndDelete(_id)
        res.send({
            status: 1,
            data,
            message: '删除客户成功'
        })
    } catch (error) {
        res.send({
            status: 0,
            message: '删除客户失败'
        })
    }
}
async function getClientsById(req, res) {
    try {
        const data = await Clients.findById(req.params._id);
        res.send({
            status: 1,
            data,
            message: '获取成功'
        })
    } catch (error) {
        res.send({
            status: 0,
            message: '获取失败'
        })
    }
}

async function addClients(req, res, next) {
        const { username, password, age,
             gender, avatarImg,insuranceTypeId,insurancesId,salesId } 
        = req.body//产品   险种   销售员
   const data= 
   await Clients.create({  username, password, age, gender, avatarImg ,insuranceTypeId,salesId,insurancesId });
   console.log(data);
    // 移动图片 
    if (avatarImg) {
        moveFiles({
            fromPath: './public/temp',
            toPath: './public/images',
            filename: avatarImg
        });
        removeFiles('./public/temp');
    }
    res.send({
        status: 1,
        message: '新增顾客成功',
        data
    })
}


module.exports = { register,getClientsById, login,addClients,deletClient,updateClient ,getClient}
